<template>
  <div style="width: 100%">
    <el-collapse v-model="activeName">
      <el-collapse-item name="1" title="基本信息">
        <el-form :disabled="dialogType==='view'" ref="form" :model="formData" :rules="rules" size="small"
                 label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="中文名称" prop="nameCn">
                <el-input v-model="formData.nameCn"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="英文名称" prop="nameEn">
                <el-input v-model="formData.nameEn"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="编码标识" prop="name">
                <el-input :disabled="dialogType!=='add'" v-model="formData.name"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="英文描述">
                <el-input v-model="formData.describeEn"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="中文描述" prop="describeCn">
                <el-input v-model="formData.describeCn"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-collapse-item>
      <el-collapse-item name="2" title="状态序列配置">
        <div class="col">
          <el-button size="small" type="primary" :disabled="dialogType==='view'"
                     @click=" $refs['gdcd'].open(selection)">插入
          </el-button>
          <el-button size="small" type="danger" :disabled="dialogType==='view'" @click="remove">移除
          </el-button>
        </div>
        <div class="col">
          <el-radio-group v-model="radio" size="small">
            <draggable tag="div" :list="selection">
              <el-radio-button v-for="{stateName,id} in selection" :label="id">{{ stateName }}</el-radio-button>
            </draggable>
          </el-radio-group>
        </div>
        <div class="col">
          <span>初始状态</span>
          <el-select size="small" :disabled="dialogType==='view'" v-model="formData.initialStateId">
            <template v-for="{stateName,id} in selection">
              <el-option :label="stateName" :value="id"></el-option>
            </template>
          </el-select>
        </div>
      </el-collapse-item>
      <el-collapse-item name="3" title="状态规则配置">
        <div class="col">
          <span>关联流程</span>
          <el-select clearable size="small" :disabled="dialogType==='view'" v-model="radioModel.flowTemplateId">
            <template v-for="{key,name} in flowList">
              <el-option :value="key" :label="name"></el-option>
            </template>
          </el-select>
        </div>

        <el-table
            size="mini"
            :data="selection"
            height="300"
            border
            style="width: 100%">
          <el-table-column
              align="center"
              prop="stateName"
              label="操作">
          </el-table-column>
          <el-table-column
              align="center"
              prop="editTo"
              label="允许修改到">
            <template slot-scope="{row}">
              <el-checkbox :value="radioModel.allowModifiableState.includes(row.id)"
                           :disabled="dialogType==='view'"
                           @change="(v)=>changeEditTo(v,row)">
              </el-checkbox>
            </template>
          </el-table-column>
          <el-table-column
              align="center"
              prop="reviseTo"
              label="允许修订到">
            <template slot-scope="{row}">
              <el-checkbox
                  :disabled="dialogType==='view'?true:(radioModel.allowRevisableState.length===1&&!radioModel.allowRevisableState.includes(row.id))"
                  :value="radioModel.allowRevisableState.includes(row.id)"
                  @change="(v)=>changeReviseTo(v,row)">
              </el-checkbox>
            </template>
          </el-table-column>
        </el-table>
      </el-collapse-item>
    </el-collapse>

    <div class="md-component-btns">
      <el-button size="medium" type="primary" v-if="dialogType!=='view'" @click="save">保存</el-button>
      <el-button size="medium" @click="$emit('removeThisTabs')">取消</el-button>
    </div>

    <get-data-common-dialog title="选择"
                            :column="column"
                            :isPage="false"
                            ref="gdcd"
                            @addToList="addToList"
                            idKey="id"
                            url="/api/state-api/life-cycle-state/list">
    </get-data-common-dialog>
  </div>
</template>
<script>
import * as api from "@/api/settingManage/lifeCycle"
import GetDataCommonDialog from "@/views/DMDComponent/getDataCommonDialog.vue";
import request from "@/router/axios";
import draggable from "vuedraggable";

export default {
  name: "lifeCycleTemp",
  components: {GetDataCommonDialog, draggable},
  data() {
    return {
      radio: "",
      activeName: ["1", "2", "3"],

      formData: {
        "nameEn": "",
        "name": "",
        "nameCn": "",
        "describeEn": "",
        "describeCn": "",
        "initialStateId": "",//初始状态id
        "stLifeCycleStateRefVoList": []
      },
      rules: {
        nameCn: [{required: true, trigger: 'blur', message: "请输入中文名称"}],
        name: [{
          required: true,
          trigger: 'blur',
          message: "请输入编码标识"
        }, {pattern: '^[A-Za-z][A-Za-z0-9_]{1,29}$', message: '请输入正确编码标识'}],
        nameEn: [{required: true, trigger: 'blur', message: "请输入英文名称"}],
        describeCn: [{required: true, trigger: 'blur', message: "请输入中文描述"}],
      },

      selection: [],
      column: [
        {prop: "stateName", label: "名称"},
        {prop: "stateCode", label: "状态"},
      ],

      flowList: [],

      dialogType: "add",

      stateList: []
    }
  },
  computed: {
    radioModel() {
      let model = {};
      if (this.formData.stLifeCycleStateRefVoList && this.formData.stLifeCycleStateRefVoList.length > 0) {
        this.formData.stLifeCycleStateRefVoList.forEach(item => {
          if (this.radio === item.lifeCycleStateId) {
            model = item;
          }
        })
      }
      return model;
    },
  },
  methods: {
    changeEditTo(v, row) {
      if (v) {
        this.radioModel.allowModifiableState.push(row.id);
      } else {
        let index = this.radioModel.allowModifiableState.indexOf(row.id);
        if (index !== -1) {
          this.radioModel.allowModifiableState.splice(index, 1);
        }
      }
    },
    changeReviseTo(v, row) {
      if (v) {
        this.radioModel.allowRevisableState.push(row.id);
      } else {
        let index = this.radioModel.allowRevisableState.indexOf(row.id);
        if (index !== -1) {
          this.radioModel.allowRevisableState.splice(index, 1);
        }
      }
    },
    addToList(list) {
      let data = this.deepCopy(list);
      let formRulesList = !this.formData.stLifeCycleStateRefVoList ? [] : this.deepCopy(this.formData.stLifeCycleStateRefVoList);
      //获取 formData 中已有的数据id集合
      let ids = formRulesList.map(item => item.lifeCycleStateId);
      // 默认选中第一个
      this.radio = list[0].id;
      // 给列表 多选框添加初始值
      data.forEach(item => {
        Object.assign(item, {editTo: false, reviseTo: false});
      })
      this.selection = data;

      list.forEach(item => {
        if (!ids.includes(item.id)) {
          formRulesList.push({
            "flowTemplateId": "", // 工作流id
            "lifeCycleStateId": item.id,//状态Id
            "allowModifiableState": [],//允许修改到
            "allowRevisableState": [], //允许修订到
          })
        }
      })
      this.$set(this.formData, "stLifeCycleStateRefVoList", formRulesList);
      this.$refs["gdcd"].close();
    },
    remove() {
      let ids = this.selection.map(item => item.id);
      this.selection.splice(ids.indexOf(this.radio), 1);

      this.formData.initialStateId = "";

      let form = this.deepCopy(this.formData);
      let lifeCycleStateIds = form.stLifeCycleStateRefVoList.map(i => i.lifeCycleStateId);

      form.stLifeCycleStateRefVoList.splice(lifeCycleStateIds.indexOf(this.radio), 1);

      let stLifeCycleStateRefVoList = form.stLifeCycleStateRefVoList;

      stLifeCycleStateRefVoList.forEach(item => {
        let index = item.allowModifiableState.indexOf(this.radio);
        let inx = item.allowRevisableState.indexOf(this.radio);
        item.allowRevisableState.includes(this.radio) ? item.allowRevisableState.splice(inx, 1) : '';
        item.allowModifiableState.includes(this.radio) ? item.allowModifiableState.splice(index, 1) : '';
      })

      this.$set(this, "formData", this.deepCopy(form));

      this.radio = this.selection.length > 0 ? this.selection[0].id : "";
    },

    save() {
      let form = this.deepCopy(this.formData);
      const {stLifeCycleStateRefVoList} = form;

      form.stLifeCycleStateRefVoList.forEach(item => {
        item.allowModifiableState = item.allowModifiableState.join(",")
        item.allowRevisableState = item.allowRevisableState.join(",")
      })

      this.$refs["form"].validate(f => {
        if (f) {
          if (stLifeCycleStateRefVoList.length > 0 && !form.initialStateId) {
            this.$message.warning("请选择初始状态");
          } else {
            let method = this.dialogType === "add" ? "save" : "update";
            api[method](form).then(() => {
              this.$message.success("保存成功");
              this.$emit('removeThisTabs');
              this.$emit('refresh');
            })
          }
        }
      })
    },

    open() {
      this.dialogType = "add";
    },
    edit(row) {
      this.dialogType = "edit";
      api.checkout({id: row.id}).then((res) => {
        this.$emit('refresh');
        this.getDetailsData(res);
      })

    },
    view(row) {
      this.dialogType = "view";
      api.getDetail({id: row.id}).then(res => {
        this.getDetailsData(res);
      })
    },

    getDetailsData(res) {
      let data = res.data.data;
      let d = [];

      this.formData = this.deepCopy(data);

      this.formData.stLifeCycleStateRefVoList.forEach(item => {
        if (!!item.allowModifiableState) {
          item.allowModifiableState = item.allowModifiableState.split(",");
        } else {
          item.allowModifiableState = [];
        }

        if (!!item.allowRevisableState) {
          item.allowRevisableState = item.allowRevisableState.split(",");
        } else {
          item.allowRevisableState = [];
        }
      })
      let rulesListId = this.formData.stLifeCycleStateRefVoList.map(item => item.lifeCycleStateId);

      this.stateList.forEach(i => {
        if (rulesListId.includes(i.id)) {
          d.push(i)
        }
      })

      this.addToList(d);
    },

    getFlowTemplateList() {
      api.flowTemplateList().then(res => {
        this.flowList = res.data.data;
      })
    },
    getStateList() {
      request({
        url: '/api/state-api/life-cycle-state/list',
        method: 'get',
      }).then(res => {
        this.stateList = res.data.data;
      })
    }
  },
  created() {
    this.getStateList();
    this.getFlowTemplateList();
  }
}
</script>
<style scoped lang="scss">
.col {
  margin-bottom: 20px;
  padding-left: 48px;

  > span {
    line-height: 36px;
    padding: 0 12px 0 0;
  }
}
</style>
